
package com.av.torrent;

import com.av.torrent.jobs.GetAllTorrentsInfoJob;
import com.av.torrent.jobs.manager.subscriber.Subscriber;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;

import java.util.ArrayList;

/**
 * @author Uladzimir_Kerus
 */
public class MainListActivity extends ListActivity {

  ArrayAdapter<String> mArrayAdapter;

  /**
   * Called when the activity is first created.
   */
  @Override
  public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getListView().setTextFilterEnabled(true);
    mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
    setListAdapter(mArrayAdapter);

    final GetAllTorrentsInfoJob getAllTorrentsInfoJob = new GetAllTorrentsInfoJob();
    getAllTorrentsInfoJob.addSubscriber(new Subscriber<JSONObject>() {

      @Override
      public void onPreExecute() {
        // TODO Auto-generated method stub
      }

      @Override
      public void onFinished(JSONObject result) {
        try {

          final ArrayList<String> torrentNameList = new ArrayList<String>();

          JSONArray torrents = result.getJSONObject("arguments").getJSONArray("torrents");
          for (int i = 0; i < torrents.length(); ++i) {
            final JSONObject torrent = torrents.getJSONObject(i);
            torrentNameList.add(torrent.getString("name"));
          }
          mArrayAdapter.clear();
          for (String torrentName : torrentNameList) {
            mArrayAdapter.add(torrentName);
          }
        } catch (JSONException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

      @Override
      public void onError(Exception exception) {
        // TODO Auto-generated method stub

      }

      @Override
      public void onAddedToQueue() {
        // TODO Auto-generated method stub

      }
    });
    Application.getInstance().getJobManager().addJob(getAllTorrentsInfoJob, true);
  }

  @Override
  public boolean onCreateOptionsMenu(final Menu menu) {
    menu.add(Menu.NONE, 0, 0, "Settings");
    return super.onCreateOptionsMenu(menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case 0:
        startActivity(new Intent(this, SettingsActivity.class));
        return true;
    }
    return false;
  }

}
